package com.gcph.zhuoba.main.Fragment;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.VideoView;

import com.gcph.zhuoba.R;
import com.gcph.zhuoba.main.activitys.MainActivity;
import com.gcph.zhuoba.main.activitys.ResourceDetailActivity;
import com.gcph.zhuoba.main.common.Constant;
import com.gcph.zhuoba.player.activitys.AnswerDetailActivity;
import com.gcph.zhuoba.player.activitys.OnlineHelpDetailActivity;
import com.gcph.zhuoba.player.activitys.PracticeDetailActivity;
import com.gcph.zhuoba.util.DownImage;
import com.gcph.zhuoba.util.L;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 台球圈
 * 
 * @author zhanghejie
 */
public class CircleFragment extends Fragment {
	private PullToRefreshListView mPullRefreshListView;

	private static LinkedList<Map<String, Object>> mListItems;
	private static int VIEW_TYPE_JIAOAN = 0;
	private static int VIEW_TYPE_LIANXI = 1;
	private static int VIEW_TYPE_QIUZHU = 2;
	private static int VIEW_TYPE_JIEDA = 3;

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View circleLayout = inflater.inflate(R.layout.layout_circle, container, false);
		// 初始化列表
		initListView(circleLayout);
		// 初始化头部按钮
		initBtnGanhuo(circleLayout);
		// 初始化头部按钮
		initBtnJiaoan(circleLayout);

		return circleLayout;
	}

	@Override
	public void onResume() {
		super.onResume();
		// 初始化列表
		initListView(getView());
	}

	/**
	 * 初始化消息按钮点击事件
	 * 
	 * @param circleLayout
	 */
	public void initBtnGanhuo(View circleLayout) {
		Button btnGanhuo = (Button) circleLayout.findViewById(R.id.btn_ganhuo);
		btnGanhuo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 点击干货按钮跳转到干货首页
				FragmentManager fManager = getFragmentManager();
				FragmentTransaction fTransaction = fManager.beginTransaction();
				((MainActivity) getActivity()).hideFragments(fTransaction);
				CircleGanhuoFragment circleGanhuoFragment = new CircleGanhuoFragment();
				fTransaction.replace(R.id.content, circleGanhuoFragment, "circleGanhuoFragment");
				fTransaction.commit();
			}
		});
	}
	
	
	/**
	 * 初始化教案按钮点击事件
	 * @param circleLayout
	 */
	public void initBtnJiaoan(View circleLayout) {
		Button btnJiaoan = (Button) circleLayout.findViewById(R.id.btn_jiaoan);
		btnJiaoan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 点击干货按钮跳转到干货首页
				FragmentManager fManager = getFragmentManager();
				FragmentTransaction fTransaction = fManager.beginTransaction();
				((MainActivity) getActivity()).hideFragments(fTransaction);
				CircleJiaoanFragment circleJiaoanFragment = new CircleJiaoanFragment();
				fTransaction.replace(R.id.content, circleJiaoanFragment, "circleJiaoanFragment");
				fTransaction.commit();
			}
		});
	}

	/**
	 * 初始化列表
	 * 
	 * @param circleLayout
	 */
	public void initListView(View circleLayout) {
		mPullRefreshListView = (PullToRefreshListView) circleLayout.findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(refreshView.getContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
				new GetDataTask().execute();
			}
		});
		
		//初始化列表数据
		if(null == mListItems || 0==mListItems.size())
		{
			new GetDataTask().execute();
		}else
		{
			CircleAdapter cAdapter = new CircleAdapter(mPullRefreshListView.getContext(),mListItems);
			mPullRefreshListView.setAdapter(cAdapter);
			cAdapter.notifyDataSetChanged();
			
			mPullRefreshListView.onRefreshComplete();
		}

		mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				TextView resourceIdView = (TextView) view.findViewById(R.id.resource_id);
				String resourceId = resourceIdView.getText().toString();
				TextView resourceDescView = (TextView) view.findViewById(R.id.resource_desc);
				String resourceDesc = resourceDescView.getText().toString();
				
				//Object resourceTypeObj = mListItems.get(position).get("resourceType");
				//L.d("resourceTypeObj"+resourceTypeObj);
				
				TextView resourceTypeTextView = (TextView) view.findViewById(R.id.resource_type_text);
				if(null == resourceTypeTextView || resourceTypeTextView.getText()==null)
				{
					return;
				}
				String resourceType = resourceTypeTextView.getText().toString();
		    	if(resourceType.contains("炫"))
				{
		    		// 跳转到详情页
					Intent intent = new Intent(getActivity(), ResourceDetailActivity.class);
					intent.putExtra("resourceId", resourceId);
					intent.putExtra("resourceDesc", resourceDesc);
					startActivity(intent);
				}else if(resourceType.contains("赏"))
				{
					Intent intent = new Intent(getActivity(), OnlineHelpDetailActivity.class);
					intent.putExtra("resourceId", resourceId);
					intent.putExtra("resourceDesc", resourceDesc);
					startActivity(intent);
				}

			}
		});
	}

	/**
	 * 异步读取列表数据
	 * @author zhanghejie
	 */
	private class GetDataTask extends AsyncTask<Void, Void, Map<String, Object>> {

		@Override
		protected Map<String, Object> doInBackground(Void... params) {
			L.d("台球圈查询列表");
			HttpUtils http = new HttpUtils();
			http.configCurrentHttpCacheExpiry(0l);//不缓存请求数据
			http.send(HttpRequest.HttpMethod.GET, getResources().getString(R.string.api_resource_list),
					new RequestCallBack<String>() {
						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							String response = responseInfo.result;
							if (response == null || "".equals(response))
								return;
							mListItems = getFormatData(response);
							CircleAdapter cAdapter = new CircleAdapter(mPullRefreshListView.getContext(),mListItems);
							mPullRefreshListView.setAdapter(cAdapter);
							cAdapter.notifyDataSetChanged();
							mPullRefreshListView.onRefreshComplete();
						}

						@Override
						public void onFailure(HttpException error, String msg) {
						}
					});

			return null;
		}

	}

	/**
	 * 格式化数据
	 * 
	 * @param result
	 * @return
	 */
	private LinkedList<Map<String, Object>> getFormatData(String data) {
		JSONObject jsonObject;

		LinkedList<Map<String, Object>> list = new LinkedList<Map<String, Object>>();

		try {
			jsonObject = new JSONObject(data);
			JSONArray jsonArray = jsonObject.getJSONArray("items");
			if (jsonArray == null)
				return null;
			for (int i = 0; i < jsonArray.length(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				JSONObject jsonItem = jsonArray.getJSONObject(i);
				if (jsonItem != null) {
					L.d("jsonItem==="+jsonItem);
						int id = jsonItem.getInt("id");
						String desc = jsonItem.getString("resourceDesc");
						String imgFileUrl = jsonItem.getString("imgFileUrl");
						String videoFileUrl = jsonItem.getString("videoFileUrl");
						String resourceTypeS = jsonItem.getString("resourceType");
						String resourceSmallTypeS = jsonItem.getString("resourceSmallType");
						String money = jsonItem.getString("money");
						Integer resourceType = null;
						Integer	resourceSmallType = null;
						if(null != resourceTypeS && null != resourceSmallTypeS && !"".equals(resourceTypeS) && !"".equals(resourceSmallTypeS)&& !"null".equals(resourceTypeS) && !"null".equals(resourceSmallTypeS))
						{
							resourceType = Integer.parseInt(resourceTypeS);
							resourceSmallType = Integer.parseInt(resourceSmallTypeS);
							map.put("resourceType", resourceType);
							map.put("resourceSmallType", resourceSmallType);
						}
						map.put("resource_img", imgFileUrl);
						map.put("videoFileUrl", videoFileUrl);
						map.put("resource_id", id);
						map.put("resource_desc", desc);
						map.put("resource_type_text", Constant.getResourceFlagText(resourceType,money));
						list.add(map);
					
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	class CircleAdapter extends BaseAdapter {
		
		private List<Map<String, Object>> list;
		private Context mContext; 
		
		public CircleAdapter(Context context,List<Map<String, Object>> ls) {  
			list = ls;  
	        mContext = context;  
	    } 

		@Override
		public int getCount() {
			if(null == list)
			{
				return 0;
			}
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return mListItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}
		
		
	    @Override  
	    public int getItemViewType(int position) {  
	    	Object resourceTypeObj = mListItems.get(position).get("resourceType");
	    	if(Constant.RESOURCE_TYPE_JIAOAN.equals(resourceTypeObj))
			{
				return VIEW_TYPE_JIAOAN;
			}else if(Constant.RESOURCE_TYPE_LIANXI.equals(resourceTypeObj))
			{
				return VIEW_TYPE_LIANXI;
			}else if(Constant.RESOURCE_TYPE_QIUZHU.equals(resourceTypeObj))
			{
				return VIEW_TYPE_QIUZHU;
			}else if(Constant.RESOURCE_TYPE_JIEDA.equals(resourceTypeObj))
			{
				return VIEW_TYPE_JIEDA;
			}
	        return VIEW_TYPE_JIAOAN;
	    }  
	  
	    @Override  
	    public int getViewTypeCount() {  
	        return 4;  
	    }  

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater  inflater = LayoutInflater.from(mContext);  
			
			int itemViewType = getItemViewType(position);
			if(itemViewType == VIEW_TYPE_JIAOAN)
			{
				convertView = inflater.inflate(R.layout.item_circle_list_jiaoan,parent, false); 
			}else if(itemViewType== VIEW_TYPE_QIUZHU)
			{
				convertView = inflater.inflate(R.layout.item_circle_list_qiuzhu,parent, false); 
			}else if(itemViewType== VIEW_TYPE_LIANXI)
			{
				convertView = inflater.inflate(R.layout.item_circle_list_lianxi,parent, false); 
			}else if(itemViewType== VIEW_TYPE_JIEDA)
			{
				convertView = inflater.inflate(R.layout.item_circle_list_bangmang,parent, false); 
			}
			
			if(itemViewType == VIEW_TYPE_JIAOAN || itemViewType == VIEW_TYPE_QIUZHU)
			{
				ImageView resource_img = (ImageView)convertView.findViewById(R.id.resource_img);
				// 如果存在网络图片，需要网络加载
				DownImage downImage = new DownImage(resource_img);
				downImage.execute(getResources().getString(R.string.server_root_url) + list.get(position).get("resource_img"));
			}else
			{
				final String videoFileUrl = String.valueOf(list.get(position).get("videoFileUrl"));
				if(null != videoFileUrl && !"".equals(videoFileUrl) && !"null".equals(videoFileUrl))
				{
					final VideoView videoView = (VideoView)convertView.findViewById(R.id.practice_video_view);
					final LinearLayout video_layout = (LinearLayout)convertView.findViewById(R.id.video_layout);
					final ProgressBar loading_video = (ProgressBar)convertView.findViewById(R.id.loading_video);
					
					video_layout.setOnClickListener(new View.OnClickListener() {
			            @Override
			            public void onClick(View arg0) {
			            	video_layout.setOnClickListener(null);
			            	videoView.setBackgroundDrawable(null);
			            	loading_video.setVisibility(View.VISIBLE);
			            	//视频加载完成
							videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
								@Override
								public void onPrepared(MediaPlayer mp) {
									loading_video.setVisibility(View.INVISIBLE);
									videoView.start();
								}
							});
			            	downLoadVedio(videoView,videoFileUrl);
			            }
			        });
					
				}
				
				//单击评论 打开练习或解答的详情页
				ImageView resource_operate = (ImageView)convertView.findViewById(R.id.resource_operate);
				final int  s_position = position;
				resource_operate.setOnClickListener(new View.OnClickListener() {
		            @Override
		            public void onClick(View arg0) {
		            	Intent intent = null;
						int rs_type = getItemViewType(s_position);
		            	//如果练习
		            	if(rs_type == VIEW_TYPE_LIANXI)
		            	{
		            		 intent = new Intent(getActivity(), PracticeDetailActivity.class);
		            	}else if(rs_type == VIEW_TYPE_JIEDA)
		            	{
		            		 intent = new Intent(getActivity(), AnswerDetailActivity.class);
		            	}
		            	
		            	if(null != intent)
		            	{
		            		intent.putExtra("resourceId", String.valueOf(list.get(s_position).get("resource_id")));
							intent.putExtra("resourceDesc", String.valueOf(list.get(s_position).get("resource_desc")));
							//intent.putExtra("parentResourceType", String.valueOf(list.get(s_position).get("resource_type_text")).replace("练习", ""));
							startActivity(intent);
		            	}
		            }
		        });
			}
			
			TextView resource_id = (TextView)convertView.findViewById(R.id.resource_id);
			TextView resource_desc = (TextView)convertView.findViewById(R.id.resource_desc);
			TextView resource_type_text = (TextView)convertView.findViewById(R.id.resource_type_text);
			
			resource_desc.setText(String.valueOf(list.get(position).get("resource_desc")));
			resource_id.setText(String.valueOf(list.get(position).get("resource_id")));
			resource_type_text.setText(String.valueOf(list.get(position).get("resource_type_text")));
			return convertView;
		}
		
		/**
		 * 根据url得文件名
		 * @param url
		 * @return
		 */
		private String getFileNameFromUrl(String url)
		{
			String fileName = null;
			if(null != url)
			{
				int index = url.lastIndexOf("/");
				fileName = url.substring(index);
			}
			return fileName;
		}
		
		/*
		 * 下载视频，并保存到存储卡
		 */
		private void downLoadVedio(final VideoView videoView,final String remoteFileUrl)
		{
			HttpUtils http = new HttpUtils();
			String url = getResources().getString(R.string.server_root_url) +remoteFileUrl;
			String fileName = getFileNameFromUrl(remoteFileUrl);
			final String  target = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+fileName;
			
			File file =new File(target);
			if(file.exists())
			{
				videoView.setVideoURI(Uri.parse(target));
				MediaController mediaco = new MediaController(mContext);
				videoView.setMediaController(mediaco);
				mediaco.setMediaPlayer(videoView);
				return ;
			}
			
	        http.download(url, target, true, true, new RequestCallBack<File>() {  
	                    @Override  
	                    public void onStart() {  
	                    	L.d("=====开始下载=====");
	                    }  

	                    @Override  
	                    public void onLoading(long total, long current, boolean isUploading) {  
	                    	int rate = (int) ((double) current/ (double) total *100);
	                        L.d("=====下载进度====="+rate);
	                    }  

	                    @Override  
	                    public void onSuccess(ResponseInfo<File> responseInfo) { 
	                    	
	                    	videoView.setVideoURI(Uri.parse(target));
							MediaController mediaco = new MediaController(mContext);
							videoView.setMediaController(mediaco);
							mediaco.setMediaPlayer(videoView);
	                    }  

	                    @Override  
	                    public void onFailure(HttpException error, String msg) {  
	                    	
	                    	 L.d("下载失败====");
	                    }
	                });  
		}
	}

	/**
	 * 列表数据绑定处理类
	 * 
	 * @author heroz
	 *
	 */
	class MyViewBinder implements ViewBinder {
		/**
		 * view：要板顶数据的视图 data：要绑定到视图的数据
		 * textRepresentation：一个表示所支持数据的安全的字符串，结果是data.toString()或空字符串，但不能是Null
		 * 返回值：如果数据绑定到视图返回真，否则返回假
		 */
		@Override
		public boolean setViewValue(View view, Object data, String textRepresentation) {
			if ((view instanceof ImageView) & (data instanceof String)) {
				ImageView iv = (ImageView) view;
				Drawable defaultDrawable = getResources().getDrawable(R.drawable.default_img);
				if (data != null && !"".equals(data) && !"null".equals(data)) {
					// 如果存在网络图片，需要网络加载
					DownImage downImage = new DownImage(iv);
					downImage.execute(getResources().getString(R.string.server_root_url) + data);
				} else {
					iv.setImageDrawable(defaultDrawable);
				}
				return true;
			}
			return false;
		}

	}

}